/**
 * Created with JetBrains PhpStorm.
 * User: yuri
 * Date: 11/12/14
 * Time: 1:24 PM
 * To change this template use File | Settings | File Templates.
 */
define(function(){
    var dev = 'app_dev.php';
    var routes = [
                    {hash:'/', controller:'startCtrl'},
                    {hash:'/page/main-menu', controller:'MenuCtrl'},
                    {hash:'/restaurant-news', controller:'NewsCtrl'},
                    {hash:'/page/contacts', controller:'ContactCtrl'},
                    {hash:'/page/gallery', controller:'GalleryCtrl'},
                    {hash:'/gallery/interior', controller:'GalleryCtrl'},
                    {hash:'/gallery/dishes', controller:'GalleryCtrl'}
                 ];

    var startRouting = {};

    startRouting.start =function(){
        hashCheck();
        return true;
    }

    function parseUrl(url){
       var newUrl = []; 
       var j = 0;
       for(var i = 0; i < url.length; i++) 
       {
           if(url[i] != dev && url[i]!="" ){
              newUrl[j] = url[i];j++;
           }
       }
       return newUrl;
    }
    
    function parseHash(routes){
       return parseUrl(routes.split('/'));
    }
    
    function isTrueUrl(url, routers){
        var result = 0;

        if(url.length !=routers.length ){
            return false;
        }
        for(var j = 0; j < routers.length; j++)
        {   
            for(var i = 0; i < url.length; i++ ){             
               if(routers[j].indexOf('{') == -1){ 
                    if(url[i].indexOf(routers[j]) > -1)
                    {
                        result++;
                    }
               } 
               else
               {
                   result++;
                   break;
               }
            }
        }
        return result == url.length;
    }

    function hashCheck(){
        var url = window.location.pathname.split('/');
        for (var i = 0; i < routes.length; i++){

            if (isTrueUrl(parseUrl(url), parseHash(routes[i].hash))){
                loadController(routes[i].controller);
            }
        }
    }

    function loadController(controllerName){
        require(['controllers/' + controllerName], function(controller){

            controller.start();
        });
    }

    return startRouting;
});